<template>
  <div class="recharge-packages-container">
    <el-card>
      <template #header>
        <div class="header">
          <h3>充值套餐列表</h3>
          <div>
            <el-button type="success" size="small" @click="openAddDialog" style="margin-right: 10px;">
              <el-icon>
                <Plus />
              </el-icon>
              新增套餐
            </el-button>
            <el-button type="primary" size="small" @click="fetchPackages" :loading="loading">
              <el-icon>
                <Refresh />
              </el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="packages" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="套餐名称" width="150" />
        <el-table-column label="价格" width="120" align="right">
          <template #default="{ row }">
            ¥{{ row.price_yuan || (row.amountCent / 100).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="points" label="积分" width="120" align="center" />
        <el-table-column label="热门" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getIsHotValue(row) ? 'danger' : 'info'" size="small">
              {{ getIsHotValue(row) ? '热门' : '常规' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'warning'" size="small">
              {{ row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="openEditDialog(row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 修改套餐对话框 -->
    <el-dialog v-model="editDialogVisible" :title="`修改套餐 - ${currentEdit.name}`" width="500px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="套餐名称">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="价格(元)">
          <el-input-number 
            v-model="editForm.price_yuan" 
            :min="0.01" 
            :precision="2" 
            :step="0.1"
          />
        </el-form-item>
        <el-form-item label="积分">
          <el-input-number v-model="editForm.points" :min="1" />
        </el-form-item>
        <el-form-item label="热门套餐">
          <el-radio-group v-model="editForm.isHot">
            <el-radio :label="1">热门套餐</el-radio>
            <el-radio :label="0">常规套餐</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="editForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新增套餐对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增套餐" width="500px">
      <el-form :model="addForm" label-width="100px" :rules="formRules" ref="addFormRef">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入套餐名称" />
        </el-form-item>
        <el-form-item label="价格(元)" prop="price_yuan">
          <el-input-number 
            v-model="addForm.price_yuan" 
            :min="0.01" 
            :precision="2" 
            :step="0.1"
            placeholder="请输入价格"
          />
        </el-form-item>
        <el-form-item label="积分" prop="points">
          <el-input-number v-model="addForm.points" :min="1" placeholder="请输入积分" />
        </el-form-item>
        <el-form-item label="热门套餐">
          <el-radio-group v-model="addForm.isHot">
            <el-radio :label="1">热门套餐</el-radio>
            <el-radio :label="0">常规套餐</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="addForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Plus } from '@element-plus/icons-vue'
import rechargeApi from '/src/api/rechargeApi.js'

const packages = ref([])
const loading = ref(false)
const editDialogVisible = ref(false)
const addDialogVisible = ref(false)
const addFormRef = ref()
const currentEdit = ref({})

const editForm = ref({
  name: '',
  price_yuan: 0,
  points: 0,
  isHot: 0,
  status: 1
})

const addForm = reactive({
  name: '',
  price_yuan: 0,
  points: 0,
  isHot: 0,
  status: 1
})

const formRules = {
  name: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
  price_yuan: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  points: [{ required: true, message: '请输入积分', trigger: 'blur' }]
}

// 获取热门状态值（兼容新旧字段）
const getIsHotValue = (row) => {
  return row.isHot !== undefined ? row.isHot : row.is_hot
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-')
}

const openAddDialog = () => {
  addForm.name = ''
  addForm.price_yuan = 0
  addForm.points = 0
  addForm.isHot = 0
  addForm.status = 1
  addDialogVisible.value = true
}

const openEditDialog = (row) => {
  currentEdit.value = row
  editForm.value = {
    name: row.name,
    price_yuan: row.price_yuan || (row.amountCent / 100),
    points: row.points,
    isHot: getIsHotValue(row),
    status: row.status
  }
  editDialogVisible.value = true
}

const fetchPackages = async () => {
  try {
    loading.value = true
    const response = await rechargeApi.getPackages()
    packages.value = response.data.data.map(item => ({
      ...item,
      price_yuan: item.amountCent / 100,
      createdTime: item.createdTime || item.created_time
    }))
  } catch (error) {
    ElMessage.error(`获取套餐失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

const submitAdd = async () => {
  try {
    await addFormRef.value.validate()
    
    loading.value = true
    const dataToSend = {
      name: addForm.name,
      amountCent: Math.round(addForm.price_yuan * 100),
      points: addForm.points,
      isHot: addForm.isHot,
      status: addForm.status
    }

    const response = await rechargeApi.addPackage(dataToSend)
    
    if (response.data.code === 200 || response.data === "新增成功") {
      ElMessage.success(response.data.message || '新增成功')
      addDialogVisible.value = false
      fetchPackages()
    } else {
      throw new Error(response.data.message || '新增失败')
    }
  } catch (error) {
    if (error.message !== 'VALIDATE_ERROR') {
      ElMessage.error(error.message || '新增失败')
    }
  } finally {
    loading.value = false
  }
}

const submitEdit = async () => {
  try {
    loading.value = true
    const dataToSend = {
      id: currentEdit.value.id,
      name: editForm.value.name,
      amountCent: Math.round(editForm.value.price_yuan * 100),
      points: editForm.value.points,
      isHot: editForm.value.isHot,
      status: editForm.value.status
    }

    const response = await rechargeApi.updatePackage(currentEdit.value.id, dataToSend)
    
    if (response.data.code === 200 || response.data === "修改成功") {
      ElMessage.success(response.data.message || '修改成功')
      editDialogVisible.value = false
      fetchPackages()
    } else {
      throw new Error(response.data.message || '更新失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '修改失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchPackages()
})
</script>

<style scoped>
.recharge-packages-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.el-table {
  margin-top: 15px;
}

.el-tag {
  margin: 2px;
}
</style>